package com.cw.jeeyt.service.intf.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.cw.jeeyt.common.utils.StringUtil;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.model.security.SecurityResourceDo;
import com.cw.jeeyt.service.impl.cache.OperationCache;

/**
 * RuoYi首创 自定义权限实现，ss取自SpringSecurity首字母
 *
 * @author ruoyi
 */
@Service("ss")
public class PermissionService {
    @Autowired
    private OperationCache operationCache;
    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        SecurityUserBo securityUserBo = SessionUtil.getSessionUser();
        if (securityUserBo == null || StringUtil.isEmpty(SessionUtil.getUserRoles())) {
            return false;
        }
        return hasPermissions(SessionUtil.getUserRoles(), permission);
    }
    /**
     * 判断是否包含权限
     *
     * RuoYi首创 自定义权限实现，ss取自SpringSecurity首字母
     *
     * @param userRoles 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(String userRoles, String permission) {
        String[] permList = userRoles.split(",");
        if (permList != null && permList.length > 0) {
            for (String perm : permList) {
                List<SecurityResourceDo> resourceList = (List<SecurityResourceDo>) operationCache.getOperations(
                    perm);
                String resourceInfo = JSON.toJSONString(resourceList);
                if (!StringUtils.isEmpty(resourceInfo)) {
                    if (resourceInfo.contains(permission)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
